package ui.face
{

	import flash.display.Bitmap;
	import flash.display.Shape;
	import flash.display.Sprite;

	import globals.Global;

	import ui.component.GameTextField;

	public class Bar extends Sprite
	{
		private var _current:Number;
		private var _max:Number;
		private var _track:Bitmap;
		private var _bg:Bitmap;
		private var _mask:Shape;
		private var _textField:GameTextField;
		private var _isShowText:Boolean;

		public function Bar(trackUrl:String, bgUrl:String, isShowText:Boolean = false)
		{
			super();
			_isShowText = isShowText;
			_bg = new Bitmap(Global.assetsManager.getAssetsAsBitmapData(bgUrl));
			this.addChild(_bg);

			_track = new Bitmap(Global.assetsManager.getAssetsAsBitmapData(trackUrl));
			_track.x = (_bg.width - _track.width) / 2;
			_track.y = (_bg.height - _track.height) / 2;
			this.addChild(_track);

			_mask = new Shape();
			this.addChild(_mask);
			_track.mask = _mask;

			if(isShowText)
			{
				_textField = new GameTextField();
				_textField.defaultTextFormat = GameTextField.getTextFormat();
				this.addChild(_textField);
			}
		}

		/**
		 * @param value
		 * @param max
		 * @param showPercentText 值为true的时候，是文字是显示如 50%；
		 * <br>值为false的时候，文字是显示如 50/100;
		 *
		 */
		public function update(value:Number, max:Number = -1, showPercentText:Boolean = false):void
		{
			if(max != -1)
			{
				_max = max;
			}
			_current = Math.min(value, _max);
			updateBar();

			if(_isShowText)
			{
				if(showPercentText)
				{
					_textField.mytext = int(value / max * 100) + "%";
				}
				else
				{
					_textField.mytext = value + "/" + max;
				}
				_textField.x = (_bg.width - _textField.textWidth) * 0.5;
				_textField.y = (_bg.height - _textField.textHeight) * 0.5;
			}
		}

		private function updateBar():void
		{
			_mask.graphics.clear();
			_mask.graphics.beginFill(0xFFFFFF);
			_mask.graphics.drawRect(_track.x, _track.y, _current / _max * _track.width, _track.height);
		}

		public function get textField():GameTextField
		{
			return _textField;
		}

		public function clear():void
		{
			_bg.bitmapData = _track.bitmapData = null;
		}
	}
}